package demo.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

/**
 * @author Arnold Yand
 * @since Mar 18, 2017 9:42:43 AM
 * @summary demo.forkjoin.ForkJoinDemo.java
 */
public class ForkJoinDemo {

  public static void main(String[] args) {

    Future<Integer> fjp = new ForkJoinPool().submit(new CountTask(0, 1000000));

    try {
      System.out.println("result :" + fjp.get());
    } catch (InterruptedException e) {
      e.printStackTrace();
    } catch (ExecutionException e) {
      e.printStackTrace();
    }

  }

}

class CountTask extends RecursiveTask<Integer> {

  private static final long serialVersionUID = 1L;
  private int start, end;

  public CountTask(int start, int end) {
    this.start = start;
    this.end = end;
  }

  protected Integer compute() {

    if ((end - start) <= 2) {
      int sum = 0;
      for (int i = start; i <= end; i++) {
        sum += i;
      }
      return sum;
    }

    int mid = (start + end) / 2;
    ForkJoinTask<Integer> left = new CountTask(start, mid).fork();
    ForkJoinTask<Integer> right = new CountTask(mid + 1, end).fork();

    return left.join() + right.join();
  }

}
